package com.bestcem.xm.qdes.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.qdes.controller.param.TagGroupParam;
import com.bestcem.xm.qdes.controller.param.TagParam;
import com.bestcem.xm.qdes.controller.vo.DeletedCountVo;
import com.bestcem.xm.qdes.entity.QdesTag;
import com.bestcem.xm.qdes.entity.QdesTagGroup;
import com.bestcem.xm.qdes.service.QdesTagGroupService;
import com.bestcem.xm.qdes.service.QdesTagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "模板库-标签库")
@RestController
@RequiredArgsConstructor
@RequestMapping("/qdes/qlibs")
public class TagController {

    private @NonNull QdesTagService tagService;

    private @NonNull QdesTagGroupService taggroupService;

    @ApiOperation(value = "标签库标签查询接口")
    @GetMapping("/tags")
    public XmResultJson<List<QdesTag>> getTag(@ApiParam(value = "标签组id", required = true) @RequestParam(value = "group_id") String groupId) {
        //创建查询条件对象
        LambdaQueryWrapper<QdesTag> queryWrapper = Wrappers.lambdaQuery();
        //构造查询条件
        queryWrapper
                .eq(QdesTag::getGroupId, groupId)
                .eq(QdesTag::getDeleted, 0);
        List<QdesTag> dbResult = tagService.list(queryWrapper);
        return XmResultJson.success(dbResult);
    }

    @ApiOperation(value = "标签库添加标签接口")
    @PostMapping("/tags")
    public XmResultJson<QdesTag> addTag(@RequestBody TagParam tagParam) {
        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();
        String title = tagParam.getTitle();
        String groupId = tagParam.getGroupId();
        QdesTag qdesTag = new QdesTag();
        qdesTag.setTitle(title);
        qdesTag.setGroupId(groupId);
        qdesTag.setIsOfficial(false);
        qdesTag.setIsCopyDemo(false);
        qdesTag.setCompanyId(orgId);
        qdesTag.setCreator(userId);
        //1.保存标签
        tagService.saveQdesTag(qdesTag);
        return XmResultJson.success(qdesTag);
    }

    @ApiOperation(value = "标签库删除标签接口")
    @DeleteMapping("/tags/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<DeletedCountVo> deleteTag(@PathVariable String id) {
        return XmResultJson.success(tagService.deleteTag(id));
    }

    @ApiOperation(value = "标签库修改标签名称接口")
    @PutMapping("/tags/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<QdesTag> updateTag(@PathVariable String id,
                                           @RequestBody TagParam tagParam) {
        boolean b = tagService.updateTagName(id, tagParam.getTitle());
        QdesTag qdesTag = new QdesTag();
        qdesTag.setId(id);
        if (b) {
            return XmResultJson.success(qdesTag);
        } else {
            return XmResultJson.fail(-1, "修改失败");
        }
    }

    @ApiOperation(value = "标签库添加标签组接口")
    @PostMapping("/taggroups")
    public XmResultJson<QdesTagGroup> addTagGroups(@RequestBody TagParam tagParam) {
        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();
        String title = tagParam.getTitle();
        QdesTagGroup qdesTaggroup = new QdesTagGroup();
        qdesTaggroup.setTitle(title);
        qdesTaggroup.setIsOfficial(false);
        qdesTaggroup.setIsCopyDemo(false);
        qdesTaggroup.setCompanyId(orgId);
        qdesTaggroup.setCreator(userId);
        qdesTaggroup.setTagIds("[]");
        //1.保存标签
        taggroupService.save(qdesTaggroup);
        return XmResultJson.success(qdesTaggroup);
    }

    @ApiOperation(value = "标签库修改标签组名称接口")
    @PutMapping("/taggroups/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<QdesTagGroup> updateTagGroups(@PathVariable String id,
                                                      @RequestBody TagParam tagParam) {
        QdesTagGroup qdesTaggroup = new QdesTagGroup();
        qdesTaggroup.setId(id);
        qdesTaggroup.setTitle(tagParam.getTitle());
        //创建修改条件对象
        LambdaUpdateWrapper<QdesTagGroup> updateWrapper = new LambdaUpdateWrapper<>();
        //构造查询条件
        updateWrapper
                .set(QdesTagGroup::getTitle, qdesTaggroup.getTitle())
                .eq(QdesTagGroup::getId, id);
        boolean b = taggroupService.update(updateWrapper);
        if (b) {
            return XmResultJson.success(qdesTaggroup);
        } else {
            return XmResultJson.fail(-1, "修改失败");
        }
    }

    @ApiOperation(value = "标签库删除标签组接口")
    @DeleteMapping("/taggroups/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<DeletedCountVo> deleteTagGroups(@PathVariable String id) {
        return XmResultJson.success(taggroupService.removeById(id));
    }

    @ApiOperation(value = "标签库标签组查询接口")
    @GetMapping("/taggroups")
    public XmResultJson<List<TagGroupParam>> getTagGroups(@RequestParam(required = false, value = "total") String total) {
        String orgId = SecurityContextHolder.getOrgId();
        List<TagGroupParam> tagGroupParamList = new ArrayList<>();
        if (StrUtil.isNotEmpty(total)) {
            LambdaQueryWrapper<QdesTagGroup> queryWrapper = Wrappers.lambdaQuery();
            //构造查询条件
            queryWrapper
                    .eq(QdesTagGroup::getCompanyId, orgId)
                    .eq(QdesTagGroup::getDeleted, 0);
            List<QdesTagGroup> dbResult = taggroupService.list(queryWrapper);
            List<QdesTagGroup> ret = dbResult.stream().map(this::convert).collect(Collectors.toList());
            for (QdesTagGroup qdesTagGroups : ret) {
                TagGroupParam tagGroupParam = new TagGroupParam();
                BeanUtil.copyProperties(qdesTagGroups, tagGroupParam);
                tagGroupParam.setTagCount(JSONArray.parseArray(tagGroupParam.getTagIds(), String.class).size());
                tagGroupParamList.add(tagGroupParam);
            }
            return XmResultJson.success(tagGroupParamList);
        } else {
            //创建查询条件对象
            LambdaQueryWrapper<QdesTagGroup> queryWrapper = Wrappers.lambdaQuery();
            //构造查询条件
            queryWrapper
                    .eq(QdesTagGroup::getCompanyId, orgId)
                    .eq(QdesTagGroup::getDeleted, 0);
            List<QdesTagGroup> dbResult = taggroupService.list(queryWrapper);
            for (QdesTagGroup qdesTagGroups : dbResult) {
                TagGroupParam tagGroupParam = new TagGroupParam();
                BeanUtil.copyProperties(qdesTagGroups, tagGroupParam);
                tagGroupParam.setTagCount(JSONArray.parseArray(tagGroupParam.getTagIds(), String.class).size());
                tagGroupParamList.add(tagGroupParam);
            }
            return XmResultJson.success(tagGroupParamList);
        }
    }

    private QdesTagGroup convert(QdesTagGroup qdesTagGroup) {
        String tagIds = qdesTagGroup.getTagIds();
        List<String> ids = JSONUtil.toList(tagIds, String.class);
        if (!CollectionUtils.isEmpty(ids)) {
            LambdaQueryWrapper<QdesTag> wrapper = Wrappers.lambdaQuery();
            wrapper.select(QdesTag::getId, QdesTag::getTitle);
            //构造查询条件
            wrapper.in(QdesTag::getId, ids);
            List<QdesTag> list = tagService.list(wrapper);
            List<Map<String, String>> listMap = list.stream().map(s -> {
                Map<String, String> map = new HashMap<>(16);
                map.put("tag_title", s.getTitle());
                map.put("tagid", s.getId());
                return map;
            }).collect(Collectors.toList());
            qdesTagGroup.setTagIds(JSONUtil.toJsonStr(listMap));
        }
        return qdesTagGroup;
    }
}
